
$(function(){
    //发表提示
    $(".releaseBut").click(function(){
        $(".releaseLayerWrap").show()
    });
    $(".releaseLayerButNo").click(function(){
        $(".releaseLayerWrap").hide()
    });

    //选题卡 提示tab
    $(".releaseTabBut").click(function(){
        var index=$(this).index();
        $(this).addClass('on').siblings('.releaseTabBut').removeClass('on');
        $(".operTogWrap").eq(index).addClass('on').siblings('.operTogWrap').removeClass('on');
        if(index==1){
            $(".releaseBut").show();
        }else{
            $(".releaseBut").hide();
        }
    });

    //选择题点击效果
    var topicListClick=function(){
        $('.topicList').click(function(){
            $(this).addClass('on').siblings().removeClass('on')
        });
    };

    //请求数据
    var answerHand=function(datas,token){
        var history_id=datas.history_id;
        var mode=datas.mode;
        var item_info=datas.item_info;
        var group_desc=item_info.group_desc;
        var list_data=item_info.list_data;
        var content=list_data.content;
        var user_history=item_info.user_history;

        var item_seq=list_data.item_seq;
        var options=list_data.options;
        var requirements=item_info.requirements;

        //题目大标题和小标题
        var itemId=item_seq.split('.')[0];
        var itemTitle=requirements[itemId-1].requirement_desc;
        var itemTitleLen=itemTitle.indexOf('（')!==-1?itemTitle.indexOf('（'):itemTitle.indexOf('(');
        var itemBig=itemTitle.substr(2,itemTitleLen-2).replace(/\s+/g,"");
        var itemSmall=itemTitle.substr(itemTitleLen,itemTitle.length).replace(/\s+/g,"");
        $('.itemTitle').html(itemBig+'<span>'+itemSmall+'</span>');
        $(".group_desc").text(group_desc);
        String.prototype.ResetBlank=function(){
            var regEx = /\s/g;
            return this.replace(regEx, '&nbsp;');
        };
        var str2 = content.replace(/[\n]/g,"<br/>").ResetBlank();
        $(".contentB").html(str2);

        //时分秒
        var addTime=null,countTime=null;
        var totalDate=item_info.user_history.total_duration;
        var durationDate=item_info.user_history.duration;

        countTime=function(){
            $(".totalDate").text(formatSeconds(totalDate));
            $(".durationDate").text(formatSeconds(durationDate))
        };
        countTime();
        clearTimeout(times);
        addTime=function(){
            times=setTimeout(function(){
                totalDate=parseInt(totalDate)+1;
                durationDate=parseInt(durationDate)+1;
                countTime();
                addTime();
            },1000);
        };
        addTime();

        //上一题下一题按钮
        if(item_seq.split('.')[0]==1&&item_seq.split('.')[1]==1){
            $(".topicButPrev").addClass('on').attr('disabled','disabled')
        }else{
            $(".topicButPrev").removeClass('on').removeAttr('disabled')
        }
        if(item_seq.split('.')[0]==4&&item_seq.split('.')[1]==requirements[3].list_num){
            $(".topicButNext").addClass('on').attr('disabled','disabled')
        }else{
            $(".topicButNext").removeClass('on').removeAttr('disabled')
        }

        //填空题
        var expect_answer_count=list_data.expected_answer_count;
        var answerB=item_info.user_history.answer;
        $(".topicEditorWrap ul").empty();
        if(item_seq.split('.')[0]>1&&expect_answer_count>0){
            if(answerB){
                answerB=JSON.parse(item_info.user_history.answer);
            }
            $(".topicEditorWrap").show();
            for(var k=0;k<expect_answer_count;k++){
                var li;
                if(answerB&&answerB[k+1]){
                    li='<li><label>('+(k+1)+').</label><div class="topicEditor"><input type="text" name="editorTxt" value="'+answerB[k+1]+'"></div></li>';
                }else{
                    li='<li><label>('+(k+1)+').</label><div class="topicEditor"><input type="text" name="editorTxt" value=""></div></li>';
                }
                $(".topicEditorWrap ul").append(li)
            }
        }else{
            $(".topicEditorWrap").hide();
        }

        //左侧选择题列表
        if(item_seq.split('.')[0]==1){
            $(".topicListWrap").empty().show();
            for(var i=0;i<options.length;i++){
                var cal='topicList';
                if(user_history.answer!==''&&options[i].label==JSON.parse(user_history.answer)[item_seq.split('.')[0]]){
                    cal='topicList on'
                }
                var lists=' <div class="'+cal+'" data-rights="'+options[i].label+'"><div class="topicCheck"><input type="checkbox"></div><div class="topicTxt">'+options[i].label+'.'+options[i].desc+'</div></div>'
                $(".topicListWrap").append(lists);
            }
        }else{
            $(".topicListWrap").hide()
        }

        //选择题点击效果
        topicListClick();

        //根据值高亮list
        var listLight=function(){
            $(".operList").eq(itemId-1).find('ul li').each(function(){
                var dataListId=$(this).attr('data-listId');
                if(item_seq==dataListId){
                    $(this).addClass('on')
                }
            });
        };

        //右侧分类
        for(var j=0;j<requirements.length;j++){
            // console.log(j);
            var list_num=requirements[j].list_num;
            var item_status=requirements[j].item_status;
            var requirement_desc=requirements[j].requirement_desc;
            var list_name=requirement_desc.indexOf('（')!==-1?requirement_desc.indexOf('（'):requirement_desc.indexOf('(');
            var descTxt=requirement_desc.substr(0,list_name);
            var len='<div class="operTitle">'+descTxt+'<i></i></div><div class="operList"><ul>';
            for(var t=0;t<list_num;t++){
                var linghtOs='';
                if(item_status[t].have_answer){
                    linghtOs='os'
                }
                len+='<li class="'+linghtOs+'" data-listId="'+((j+1)+'.'+(t+1))+'" data-listBoll="'+item_status[t].have_answer+'">'+(t+1)+'</li>';
            };
            len+='</ul></div>';
            $('.operWrap').eq(j).html(len);
            if(list_num>0){

            }
        }
        listLight();

        //做题提示
        var publishArr={
            'auth_token':token,
            'resource_id':list_data.resource_id,
            'page_no':1,
            'page_size':18
        };
        publishEvent(publishArr);//提示
        publishEaseEvent(publishArr);//发布

        //参数
        var topicObj={
            "auth_token":token,
            "history_id":history_id||'',
            "mode":mode,
            "item_seq":item_seq,
            "item_id":datas.item_id,
            "answer":''
        };
        topicPrev(topicObj);//上一题
        topicNext(topicObj);//下一题
        operListEvent(topicObj);//跳转题目
        answerOver(topicObj);//结束答题
        answerClose(topicObj)//放弃答题
    };

    //做题提示展示
    var publishEvent=function(obj){
        if(obj){
            $.ajax({
                type: "GET",
                url:base_url + "tips/list",
                data:obj,
                beforeSend:function(XMLHttpRequest){},
                success:function(data){
                    var datas=data.data;
                    if(datas){
                        var load='<div class="loadings"><i></i></div>';
                        $(".loadings").remove();
                        var page_contents=datas.page_contents;
                        for(var i=0;i<page_contents.length;i++){
                            var nickname=page_contents[i].nickname;
                            var publish_date=page_contents[i].publish_date;
                            var tip_content=page_contents[i].tip_content;

                            var li=' <div class="releaseTestList">\n' +
                                '                        <div class="releaseTestHead clearfix">\n' +
                                '                            <div class="releases use left" style="background-image:url(\'../images/use.png\')"></div>\n' +
                                '                            <div class="releases name left">'+nickname+'</div>\n' +
                                '                            <div class="releases time right">'+publish_date+'</div>\n' +
                                '                        </div>\n' +
                                '                        <p>' +tip_content+'</p>' +
                                '                    </div>';
                            $(".operScroll").append(li)
                        }
                        $(".operScroll").append(load);
                        scrollGet(obj,page_contents)
                    }
                },
                error:function(){
                    console.log('失败')
                }
            });
        }
    };

    //滚动加载下一页
    var scrollGet=function(obj,cont){
        var pageContents=isEmptyObject(cont);
        if(!pageContents){
            var t=0;
            var p=0;
            var bool=true;
            $(".operScroll").unbind('scroll').scroll(function(e){
                t=$(this).scrollTop();
                var heights=$(this).height();
                var scrollHeights=e.delegateTarget.scrollHeight;
                if(p<=t){//console.log("向下");
                    if(bool&&t>scrollHeights-(heights+80)){
                        $(".loadings").show();
                        bool=false;
                        var obj2={
                            'auth_token':obj.auth_token,
                            'resource_id':obj.resource_id,
                            'page_no':parseInt(obj.page_no)+1,
                            'page_size':obj.page_size
                        };
                        publishEvent(obj2)
                    }else{
                        // $(".loadings").hide();
                    }
                }else{//console.log("向上")
                }
                setTimeout(function(){p=t},0)
            });
        }else {
            $(".loadings").remove();
            var load='<div class="loadings">没有数据了</div>';
            $(".operScroll").append(load);
            $(".loadings").show();
        }
    };

    //做题提示发布
    var publishEaseEvent=function(obj){
        if(obj){
            $(".releaseLayerButYes").unbind('click').click(function(){
                var contentTxt=$(".releaseLayerTxt").find("textarea");
                if(contentTxt.val()==''){
                    layTxt('内容不能为空！');
                }else{
                    var obj1= {
                        'auth_token': obj.auth_token,
                        'resource_id': obj.resource_id,
                        'content': contentTxt.val()
                    };
                    $.ajax({
                        type: "POST",
                        url:base_url + "tips/publish",
                        data:obj1,
                        beforeSend:function(XMLHttpRequest){},
                        success:function(data){
                            if(data.is_success){
                                publishEvent(obj);
                                $(".releaseLayerWrap").hide();
                            }
                        },
                        error:function(){
                            console.log('失败')
                        }

                    });
                }

            })
        }

    };

    //验证答案
    var topicTest=function(obj){
        if(obj){
            $.ajax({
                type: "POST",
                url:base_url + "practice/check",
                data:obj,
                beforeSend:function(XMLHttpRequest){},
                success:function(data){
                    if(data.is_success){
                        console.log('验证了答案')
                    }
                },
                error:function(){
                    console.log('失败')
                }

            });
        }
    };

    //上一题
    var topicPrev=function(obj){
        if(obj){
            $(".topicButPrev").unbind('click').click(function(){
                $('.topicList').each(function(){
                    if($(this).hasClass('on')){
                        var choices=new Object();
                        choices['1']=$(this).attr("data-rights");
                        obj.answer=JSON.stringify(choices)
                    }
                });
                if(obj.item_seq.split('.')[0]>1){
                    obj.answer=editorGet()
                }
                topicTest({
                    'auth_token':obj.auth_token,
                    'item_id':obj.item_id,
                    'group_type':obj.mode,
                });

                var obj2= {
                    "auth_token":obj.auth_token,
                    "history_id":obj.history_id,
                    "list_seq":obj.item_seq,
                    "mode":obj.mode,
                    "answer":obj.answer
                };
                setTimeout(function(){
                    $.ajax({
                        type: "POST",
                        url:base_url + "practice/prev",
                        data:obj2,
                        beforeSend:function(XMLHttpRequest){},
                        success:function(data){
                            var datas=data.data;
                            if(datas){
                                answerHand(datas,obj.auth_token)
                            }
                        },
                        error:function(){
                            console.log('失败')
                        }

                    });
                },500);
            });
        }

    };
    //下一题
    var topicNext=function(obj){
        if(obj){
            $(".topicButNext").unbind('click').click(function(){
                $('.topicList').each(function(){
                    if($(this).hasClass('on')){
                        var choices=new Object();
                        choices['1']=$(this).attr("data-rights");
                        obj.answer=JSON.stringify(choices)
                    }
                });
                if(obj.item_seq.split('.')[0]>1){
                    obj.answer=editorGet()
                }
                topicTest({
                    'auth_token':obj.auth_token,
                    'item_id':obj.item_id,
                    'group_type':obj.mode,
                });

                var obj2= {
                    "auth_token":obj.auth_token,
                    "history_id":obj.history_id,
                    "list_seq":obj.item_seq,
                    "mode":obj.mode,
                    "answer":obj.answer
                };
                setTimeout(function(){
                    $.ajax({
                        type: "POST",
                        url:base_url + "practice/next",
                        data:obj2,
                        beforeSend:function(XMLHttpRequest){},
                        success:function(data){
                            console.log(data);
                            var datas=data.data;
                            if(datas){
                                answerHand(datas,obj.auth_token)
                            }
                        },
                        error:function(){
                            console.log('失败')
                        }

                    });
                },500);

            });
        }

    };

    //开始答题
    var answerGet=function(token,arr){
        var arr2={
            auth_token:arr.auth_token,
            group_id:arr.group_id,
            group_type:arr.group_type,
            mode:arr.mode,
            history_id:arr.history_id
        };
        $.ajax({
            type: "POST",
            url:base_url + "practice/begin",
            data:arr2,
            beforeSend:function(XMLHttpRequest){},
            success:function(data){
                console.log(data);
                var datas=data.data;
                if(datas){
                    answerHand(datas,token)
                }
                if(!data.is_success){
                    successFalse('没有数据！')
                }
            },
            error:function(){
                successFalse('请求失败！')
            }
        })
    };
    //判断token
    if(tokens){
        var statusArr=$.cookie("statusArr");
        var statusArrBool=$.cookie('statusArrBool');
        if(statusArr){
            if(!statusArrBool){
                var arr=JSON.parse(statusArr);
                statusArr={
                    auth_token:arr.auth_token,
                    group_id:arr.group_id,
                    group_type:arr.group_type,
                    mode:arr.mode,
                    history_id:arr.history_id
                }
            }
            answerGet(tokens,JSON.parse(statusArr));
        }
    }else{
        layTxt('您还没登录!');
        setTimeout(function(){
            setUrl('overyears','login')//设置跳转
        },1000)
    }

    //跳转题目
    var operListEvent=function(obj){
        if(obj){
            $(".operList ul li").unbind('click').click(function(){
                $('.topicList').each(function(){
                    if($(this).hasClass('on')){
                        var choices=new Object();
                        choices['1']=$(this).attr("data-rights");
                        obj.answer=JSON.stringify(choices)
                    }
                });
                if(obj.item_seq.split('.')[0]>1){
                    obj.answer=editorGet()
                }
                topicTest({
                    'auth_token':obj.auth_token,
                    'item_id':obj.item_id,
                    'group_type':obj.mode,
                });
                var obj2= {
                    "auth_token":obj.auth_token,
                    "history_id":obj.history_id,
                    "list_seq_from":obj.item_seq,
                    "list_seq_to":$(this).attr('data-listid'),
                    "mode":obj.mode,
                    "answer":obj.answer
                };
                setTimeout(function(){
                    $.ajax({
                        type: "POST",
                        url:base_url + "practice/jump",
                        data:obj2,
                        beforeSend:function(XMLHttpRequest){},
                        success:function(data){
                            var datas=data.data;
                            if(datas){
                                answerHand(datas,obj.auth_token)
                            }
                        },
                        error:function(){
                            console.log('失败')
                        }
                    })
                },500);
            })
        }

    };

    //结束答题
    var answerOver=function(obj){
        if(obj){
            $(".topicButOver").unbind('click').click(function(){
                $('.topicList').each(function(){
                    if($(this).hasClass('on')){
                        var choices=new Object();
                        choices['1']=$(this).attr("data-rights");
                        obj.answer=JSON.stringify(choices)
                    }
                });
                if(obj.item_seq.split('.')[0]>1){
                    obj.answer=editorGet()
                }
                topicTest({
                    'auth_token':obj.auth_token,
                    'item_id':obj.item_id,
                    'group_type':obj.mode,
                });
                var obj2= {
                    "auth_token":obj.auth_token,
                    "history_id":obj.history_id,
                    "item_seq":obj.item_seq,
                    "answer":obj.answer
                };
                setTimeout(function(){
                    $.ajax({
                        type: "POST",
                        url:base_url + "practice/end",
                        data:obj2,
                        beforeSend:function(XMLHttpRequest){},
                        success:function(data){
                            if(data.is_success){
                                var datas=data.data;
                                var score=datas.score;
                                var total_items=datas.total_items;
                                var wrong_count=datas.wrong_count;
                                var practice_date=datas.practice_date;
                                var submit_date=datas.submit_date;
                                var practice_duration=datas.practice_duration;
                                $(".scoreWrap").show();
                                $(".scoreContent").eq(0).text(score);
                                $(".scoreContent").eq(1).text(total_items);
                                $(".scoreContent").eq(2).text(wrong_count);
                                $(".scoreContent").eq(3).text(practice_date);
                                $(".scoreContent").eq(4).text(submit_date);
                                $(".scoreContent").eq(5).text(formatSeconds(practice_duration));

                                $(".scoreBut button").unbind('click').click(function(){
                                    setTimeout(function(){
                                        setUrl('overyears','screen')//设置跳转
                                    },1000);
                                })
                            }
                        },
                        error:function(){
                            console.log('失败')
                        }
                    })
                },500);
            })
        }
    };

    //放弃答题
    var answerClose=function(obj){
        if(obj){
            $(".topicButClose").unbind('click').click(function(){
                $('.topicList').each(function(){
                    if($(this).hasClass('on')){
                        var choices=new Object();
                        choices['1']=$(this).attr("data-rights");
                        obj.answer=JSON.stringify(choices)
                    }
                });
                if(obj.item_seq.split('.')[0]>1){
                    obj.answer=editorGet()
                }
                topicTest({
                    'auth_token':obj.auth_token,
                    'item_id':obj.item_id,
                    'group_type':obj.mode,
                });
                var obj2= {
                    "auth_token":obj.auth_token,
                    "history_id":obj.history_id
                };
                setTimeout(function(){
                    $.ajax({
                        type: "POST",
                        url:base_url + "practice/cancel",
                        data:obj2,
                        beforeSend:function(XMLHttpRequest){},
                        success:function(data){
                            layTxt('您放弃了答题！');
                            setTimeout(function(){
                                setUrl('overyears','screen')//设置跳转
                                console.log('33333333333')
                            },500);
                        },
                        error:function(){
                            console.log('失败')
                        }
                    })
                },500);
            })
        }
    }
});